package com.zhangx.study.demo.rpc.client;

import com.zhangx.study.demo.rpc.server.model.User;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.Socket;

/**
 * @ClassName Stub
 * @Description TODO
 * @Author zhangx
 * @Date 2020/10/12 8:39
 **/
@Slf4j
public class Stub {

    public User findUserById(Integer id) throws IOException {
        User user = new User();
        Socket socket = new Socket("localhost",8888);
//            写入到服务端
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        DataOutputStream dataOutputStream = new DataOutputStream(out);
        dataOutputStream.writeInt(1);

        OutputStream outputStream = socket.getOutputStream();
        outputStream.write(out.toByteArray());
        outputStream.flush();

//            从服务端读取
        InputStream in = socket.getInputStream();
        DataInputStream dataInputStream = new DataInputStream(in);
        int age = dataInputStream.readInt();
        String name = dataInputStream.readUTF();
        log.info("收到服务端返回 age={},name={}",age,name);
        dataOutputStream.close();
        socket.close();

        user.setAge(age);
        user.setName(name);
        user.setId(id);
        return user;
    }
}
